package com.supreme.uploadserver.service;

import com.supreme.commonboot.exception.BizException;
import com.supreme.uploadserver.component.props.UploadServerProps;
import io.minio.*;
import io.minio.errors.MinioException;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.InputStream;

@Service
public class MinioService {

    @Resource
    private UploadServerProps uploadServerProps;

    @Resource
    private MinioClient minioClient;

    @PostConstruct
    private void initUploadBucket() {
        createBucket(uploadServerProps.getMinioBucket());
    }

    /**
     * 创建 bucket
     * @param bucketName: 桶名
     */
    @SneakyThrows(Exception.class)
    public void createBucket(String bucketName) {
        BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder().bucket(bucketName).build();
        boolean isExist = minioClient.bucketExists(bucketExistsArgs);
        if (!isExist) {
            MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build();
            minioClient.makeBucket(makeBucketArgs);
        }
    }

    /**
     * 文件上传
     * @param bucketName: 桶名
     * @param fileName: 文件名
     * @param filePath: 文件路径
     * @param contentType: 文件类型
     * @return: ObjectWriteResponse
     */
    @SneakyThrows(Exception.class)
    public ObjectWriteResponse upload(String bucketName, String fileName, String filePath, String contentType) {
        try {
            final UploadObjectArgs uploadObjectArgs = UploadObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .filename(filePath)
                    .contentType(contentType)
                    .build();
            return minioClient.uploadObject(uploadObjectArgs);
        } catch (MinioException e) {
            throw new BizException(e.getMessage());
        }
    }

    /**
     * 文件上传
     * @param bucketName: 桶名
     * @param fileName: 文件名
     * @param stream: 文件流
     * @param fileSize: 文件大小
     * @param contentType: 文件类型
     * @return: java.lang.String : 文件url地址
     */
    @SneakyThrows(Exception.class)
    public ObjectWriteResponse upload(String bucketName, String fileName, InputStream stream, long fileSize, String contentType) {
        final PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .stream(stream, fileSize, -1)
                .contentType(contentType)
                .build();
        return minioClient.putObject(putObjectArgs);
    }
}
